import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:duo_zui/constant/constant.dart';
import 'package:duo_zui/model/model.dart';
import 'package:duo_zui/router.dart';
import 'package:duo_zui/widget/common/common_loading_dialog.dart';
import 'package:duo_zui/widget/common/common_retry.dart';
import 'package:duo_zui/widget/common//common_snakeBar.dart';
import 'package:flutter/material.dart';

class Choice {
  const Choice({this.choiceName, this.choiceValue});

  final String choiceName;
  final int choiceValue;
}

const List<Choice> choices = const <Choice>[
  const Choice(choiceName: Constant.popAgree, choiceValue: 0),
  const Choice(choiceName: Constant.popReport, choiceValue: 1),
  const Choice(choiceName: Constant.popCopy, choiceValue: 2),
  const Choice(choiceName: Constant.popReply, choiceValue: 3),
];

class CommentPage extends StatefulWidget {
  int themeId;
  Post post;

  CommentPage({Key key, this.themeId, this.post}) : super(key: key);

  @override
  _CommentPageState createState() {
    return _CommentPageState();
  }
}

class _CommentPageState extends State<CommentPage>{
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
      new GlobalKey<RefreshIndicatorState>();

  final GlobalKey<ScaffoldState> _scaffoldStateKey =
      new GlobalKey<ScaffoldState>();


  int _longCommentsLength = 0;

  int _shortCommentsLength = 0;

  bool _isShowRetry = true;

  List<Comment> comments = [];

  _initData() async {
    Dio dio = new Dio();
    String url = "http://www.appshuo.club/api/client/api/comments/all/${widget.themeId}?pageNum=1&pageSize=5";
    print(url);
    Response response = await dio.get(
        url);
    Reslut reslut = Reslut.fromJson(response.data);
    setState(() {
      comments.addAll(reslut.response.comments);
      _shortCommentsLength = comments.length;
    });
  }


  @override
  void initState() {
    super.initState();
    _initData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Widget _buildNull() {
    return new Container(
      color: Colors.grey[100],
      height: 300.0,
      child: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Icon(
              Icons.desktop_mac,
              color: Colors.blue[200],
              size: 100.0,
            ),
            new Padding(
              padding: const EdgeInsets.only(top: 12.0),
              child: new Text(
                '深度长评虚位以待',
                style: new TextStyle(
                  color: Colors.blue[400],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildPopItem(Comment item) {
    return new PopupMenuButton<Choice>(
        padding: EdgeInsets.zero,
        onSelected: (choice) {
          print(choice.choiceName);
        },
        child: _buildContentItem(item),
        itemBuilder: (BuildContext context) {
          return choices.map((Choice choice) {
            return new PopupMenuItem<Choice>(
              value: choice,
              child: new Text(choice.choiceName),
            );
          }).toList();
        });
  }


  Widget _buildExpansionTileForShort() {
    return new ExpansionTile(
        initiallyExpanded: true,
        title: new Text('$_shortCommentsLength 条短评论',
            style: new TextStyle(
                fontSize: 16.0,
                fontWeight: FontWeight.w500,
                color: Colors.black)),
        children: comments.map((model) {
          return _buildPopItem(model);
        }).toList(),
    );
  }

  Widget _buildItem(BuildContext context) {
    Widget widget;
    if (comments.length != 0) {
      widget = _buildExpansionTileForShort();
    } else {
      widget = _buildTotal('$_shortCommentsLength 条短评论');
    }
    return widget;
  }

  Widget _buildTotal(String content) {
    return new Column(
      children: <Widget>[
        new Padding(
          padding: const EdgeInsets.only(
              left: 8.0, top: 12.0, bottom: 12.0, right: 12.0),
          child: new Align(
            alignment: Alignment.centerLeft,
            child: new Text(
              content,
              style: new TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.w500,
                  color: Colors.black),
            ),
          ),
        ),
        new Divider(height: 1.0),
      ],
    );
  }

  Widget _buildContentItem(Comment item) {
    return new InkWell(
      child: new Padding(
        padding: const EdgeInsets.only(left: 12.0, top: 12.0, right: 12.0),
        child: new Column(
          children: <Widget>[
            new Row(
              children: <Widget>[
                new CircleAvatar(
                  radius: 12.0,
                  backgroundImage: new NetworkImage(
                      item.user.photo == null ? Constant.defHeadimg : item.user.photo),
                ),
                new Padding(
                  padding: const EdgeInsets.only(left: 12.0, right: 12.0),
                  child: new Text('${item.user.nickname == null ? '无名氏' : item.user.nickname}',
                      style: new TextStyle(
                        fontSize: 16.0,
                        color: Colors.black,
                        fontWeight: FontWeight.w400,
                      )),
                ),
                new Expanded(
                    child: new Container(
                  child: new Align(
                    alignment: Alignment.topRight,
                    child: new Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        new Icon(
                          Icons.thumb_up,
                          color: Colors.grey,
                          size: 18.0,
                        ),
                        new Text(
                          '(${item.applaudCount})',
                          style: new TextStyle(color: Colors.grey),
                        )
                      ],
                    ),
                  ),
                )),
              ],
            ),
            new Padding(
              padding:
                  const EdgeInsets.only(left: 35.0, top: 4.0, bottom: 10.0),
              child: new Container(
                alignment: Alignment.topLeft,
                child: new Text('${item.content}',
                    style: new TextStyle(fontSize: 14.0, color: Colors.black)),
              ),
            ),
            _buildReply(item),
            new Padding(
              padding: const EdgeInsets.only(top: 12.0, bottom: 8.0),
              child: new Container(
                alignment: Alignment.topRight,
                child: new Text('${item.updateDate}'),
              ),
            ),
            new Divider(height: 1.0),
          ],
        ),
      ),
    );
  }

  Widget _buildReply(Comment item) {
    Comment replyToModel = item;

    if (null != replyToModel) {
      return new Padding(
        padding: const EdgeInsets.only(left: 35.0, bottom: 12.0),
        child: new Container(
          alignment: Alignment.topLeft,
          child: new Text.rich(
            new TextSpan(
                text: '//dd：',
                style: new TextStyle(
                    fontSize: 16.0,
                    color: Colors.black,
                    fontWeight: FontWeight.w400),
                children: [
                  new TextSpan(
                      text: 'lll',
                      style: new TextStyle(
                        fontSize: 14.0,
                        color: Colors.grey[600],
                        fontWeight: FontWeight.w400,
                      ))
                ]),
          ),
        ),
      );
    } else {
      //不需要显示怎么办？
      return new Container(
        height: 0.0,
      );
    }
  }

  Widget _buildList(BuildContext context) {
    var content;

      // content = new ListView.builder(
      //   //设置physics属性总是可滚动
      //   physics: AlwaysScrollableScrollPhysics(),
      //   itemCount: comments.length,
      //   itemBuilder: _buildItem,
      // );
    content = _buildItem(context);
    // var _refreshIndicator = new RefreshIndicator(
    //   key: _refreshIndicatorKey,
    //   onRefresh: _refreshData,
    //   child: content,
    // );

    return content;
  }

  Widget _buildBottomBar() {
    return new BottomAppBar(
      child: new InkWell(
        onTap: () {
          //RouteUtil.route2Login(context);
        },
        child: new Container(
          height: 40.0,
          child: new Center(
            child: new Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new Icon(
                  Icons.edit,
                  color: Colors.blue,
                  size: 20.0,
                ),
                new Text(
                  '写点评',
                  style: new TextStyle(fontSize: 16.0, color: Colors.blue),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldStateKey,
      backgroundColor: Colors.white,
      appBar: new AppBar(
        title: new Text("评论列表"),
        centerTitle: true,
        leading: IconButton(
          icon:Icon(Icons.arrow_back_ios,size:20) ,
          onPressed: (){
            String url = 'http://www.appshuo.club/appview/p/';
            MyRouter.push(context, MyRouter.articelPage, {'url': '$url${widget.post.id}', 'article':widget.post});
          },),
      ),
      //头部的标题AppBar
      body: _buildList(context),
      bottomNavigationBar: _buildBottomBar(),
    );
  }
}
